# -*- coding: utf-8 -*-
import re

import scrapy


class YouxinSpider(scrapy.Spider):
    name = 'youxin'
    allowed_domains = ['xin.com']
    start_urls = ['https://www.xin.com/suqian/i1/']
    page = 1

    def parse(self, response):

        a_list = response.xpath("//ul/li")

        for a_temp in a_list:
            img_url = a_temp.xpath("./@data-img").extract_first()
            title = a_temp.xpath('.//h2/span/text()').extract_first()
            data_time = a_temp.xpath(".//span/text()").extract_first()
            adr = a_temp.xpath(".//span/span/text()").extract_first()
            s_price = a_temp.xpath(".//p/em/text()").extract_first()
            f_price = a_temp.xpath(".//p[1]/span/text()").extract_first()
            subsidy = a_temp.xpath('.//p[2]/span/text()').extract_first()

            data_time_s = str(data_time).replace(' ','')
            s_price_s = str(s_price).replace('\n', '').replace(' ', '')
            f_price_s = str(f_price).replace('\n', '').replace(' ', '')
            # print('----------------------222222222222222222233333333333333333333333333333--------')
            yield {
                'type': 'info',
                '标题':title,
                '图片链接':img_url,
                '出厂年份':data_time_s,
                '地点':adr,
                '总价格':s_price_s,
                '首付':f_price_s,
                '补贴':subsidy
            }
            self.page += 1
            if self.page <= 5:
                news_url = 'https://www.xin.com/suqian/i%d' % self.page
                yield scrapy.Request(url=news_url, callback=self.parse)
                print('---------------------22222222222222222222222222')
            # title_re = re.findall(r"(.+?) ", title)[0]
            img_url01 = 'http:' + str(img_url)
            yield scrapy.Request(url=img_url01,callback=self.parse_img, cb_kwargs={"img_name": title})
    #
    def parse_img(self, response, img_name):
        yield {
            "type": "img",
            "img_name": img_name + ".png",
            "img_bytes": response.body
        }

